﻿using Cache.CSRedis;
using Common.Tools;
using Order.Domain.Entity;
using Order.Domain.Repository;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Order.Domain.DomainService
{
    public class CreateOrderService : IDomainService
    {
        private const string StockRedisKey= "StockRedisKey";
        private readonly IRedisHelper _redisHelper;
        private readonly IOrderRepository _orderRepository;
        public CreateOrderService(IRedisHelper redisHelper, IOrderRepository orderRepository)
        {
            _redisHelper = redisHelper;
            _orderRepository = orderRepository;
        }
       
        /// <summary>
        /// Lua脚本扣减redis中的库存
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public async Task<string> DeductRedisInventory()
        {
            var result = string.Empty;
            try
            {
                var script = @"local stock = redis.call('get', KEYS[1]) 
                             if stock == '0' then
                              return 0;
                             end
                              redis.call('decr', KEYS[1])
                              return 1";
                var remainderProductStock = _redisHelper.Lua(script, StockRedisKey);
                if (remainderProductStock == 0)
                {
                    result = "库存不足,抢购失败！";
                }
            }
            catch (Exception ex)
            {
                result = $"扣减库存异常！原因：{ex.Message}";
            }
            await Task.CompletedTask;
            return result;
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="customterId"></param>
        /// <param name="orderItemList"></param>
        /// <returns></returns>
        public async Task<string> CreateOrder(string customterId, List<OrderItem> orderItemList) 
        {
            var orderNo = GetGenerateOrderNo();
            var order = Domain.Entity.Order.CreateOrder(orderNo, customterId, orderItemList);
            await _orderRepository.AddOrder(order);
            return orderNo;
        }

        /// <summary>
        /// 生成订单号
        /// </summary>
        private string GetGenerateOrderNo() 
        {
            var orderNo = DateTime.Now.ToString("yyyyMMddhhmmss");
            return orderNo;
        }
    }
}
